/**
 * 格式化位置
 * @param {*} res chooseLocation成功后返回参数
 * 格式: {
	 address: "浙江省舟山市定海区昌国路61号"
	 errMsg: "chooseLocation:ok"
	 latitude: 30.019785
	 longitude: 122.106927
	 name: "舟山市定海区人民政府"
   }
 */
function formatLocation(res) {
	var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
	var REGION_PROVINCE = [];
	var addressBean = {
		REGION_PROVINCE: null,
		REGION_COUNTRY: null,
		REGION_CITY: null,
		ADDRESS: null
	};

	function regexAddressBean(address, addressBean) {
		// regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
		regex = /^(.*?[市]|.*?地区|.*?自治州|.*?特别行政区)(.*?[市区县])(.*?)$/g;
		var addxress = regex.exec(address);
		addressBean.REGION_CITY = addxress[1];
		addressBean.REGION_COUNTRY = addxress[2];
		addressBean.ADDRESS = addxress[3] + "(" + res.name + ")";
		// console.log(addxress);
	}
	if (!(REGION_PROVINCE = regex.exec(res.address))) {
		regex = /^(.*?(省|自治区))(.*?)$/;
		REGION_PROVINCE = regex.exec(res.address);
		addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
		regexAddressBean(REGION_PROVINCE[3], addressBean);
	} else {
		addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
		regexAddressBean(res.address, addressBean);
	}
	return addressBean
};
/**
 * 获取位置
 * @param {*} obj,要修改的对象
 * @param {*} address,详细地址
 * @param {*} name,位置名称
 */
function getLocation(obj, address, name) {
	uni.chooseLocation({
		 success: (res)=> {
			// console.log(res);
			var locationObj = formatLocation(res);
			obj[address] = locationObj.REGION_PROVINCE + " " +
				locationObj.REGION_CITY + " " +
				locationObj.REGION_COUNTRY;
			obj[name] = locationObj.ADDRESS;
		},
		fail: function() {
			uni.getSetting({
				success: function(res) {
					var statu = res.authSetting;
					if (!statu['scope.userLocation']) {
						uni.showModal({
							title: '是否授权当前位置',
							content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
							success: function(tip) {
								if (tip.confirm) {
									uni.openSetting({
										success: function(data) {
											if (data.authSetting["scope.userLocation"] === true) {
												uni.showToast({
													title: '授权成功',
													icon: 'success',
													duration: 1000
												})
												//授权成功之后，再调用chooseLocation选择地方
												uni.chooseLocation({
													success: function(res) {
														var locationObj = formatLocation(res);
														obj[address] = locationObj.REGION_PROVINCE + " " +
															locationObj.REGION_CITY + " " +
															locationObj.REGION_COUNTRY;
														obj[name] = locationObj.ADDRESS
													},
												})
											} else {
												uni.showToast({
													title: '授权失败',
													icon: 'none',
													duration: 1000
												})
											}
										}
									})
								}
							}
						})
					}
				},
				fail: function(res) {
					uni.showToast({
						title: '调用授权窗口失败',
						icon: 'none',
						duration: 1000
					})
				}
			})
		}
	})
};
module.exports = {
	getLocation,
	formatLocation
}
